import { Injectable } from '@nestjs/common';
import { CreateGoodDto } from './dto/create-good.dto';
import { UpdateGoodDto } from './dto/update-good.dto';
import { Good } from './entities/good.entity';
import { Article } from "../article/entities/article.entity"
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { unlinkSync } from "fs"
import { join } from 'path';
@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Good) private readonly goods: Repository<Good>,
    @InjectRepository(Article) private readonly articles: Repository<Article>
  ) { }
  create(createGoodDto: CreateGoodDto) {
    const good = new Good()
    const article = new Article()
    good.name = createGoodDto.name
    good.price = createGoodDto.price
    good.description = createGoodDto.description
    good.img = createGoodDto.img
    good.type = createGoodDto.type
    good.num = createGoodDto.num
    article.description = createGoodDto.description
    article.img = createGoodDto.img
    article.name = createGoodDto.name
    article.type = createGoodDto.type
    article.worth = createGoodDto.price
    this.goods.save(good)
    this.articles.save(article)
    return {
      message: '添加成功',
      code: 200
    }
  }

  async findAll(query: { keyword: string, page: number, pageSize: number }) {
    const [result, total] = await this.goods.findAndCount({
      where: [
        { name: Like(`%${query.keyword}%`) },
        { type: Like(`%${query.keyword}%`) },
      ],
      order: { id: "ASC" },
      skip: (query.page - 1) * query.pageSize,
      take: query.pageSize
    })
    return { result, total }
  }

  findOne(id: number) {
    return `This action returns a #${id} good`;
  }

  async update(id: number, updateGoodDto: UpdateGoodDto) {
    // 删除原图片
    const originalGood = await this.goods.findOneBy({ id })
    if (originalGood.img !== updateGoodDto.img) {
      unlinkSync(join(__dirname, '..', '../public', 'img', `${originalGood.img}`));
    }
    await this.goods.update(id, updateGoodDto)
    return {
      message: '修改成功',
      code: 200
    }
  }

  async remove(id: number) {
    // 删除图片
    const deletedGood = await this.goods.findOneBy({ id })
    unlinkSync(join(__dirname, '..', '../public', 'img', `${deletedGood.img}`))
    await this.goods.delete(id)
    return {
      message: '删除成功',
      code: 200
    }
  }
}
